#!/bin/bash

cd $HOME/tmp/circuit/cluster/127.0.0.1/*/lang
LANGDIR=$PWD
cd Chan
mkdir c1 c2
echo 0 >> c1/cap
echo 0 >> c2/cap
cd ../Select
mkdir s1
cat <<EOF >> s1/cases_lines
$LANGDIR/Chan/c1/recv
$LANGDIR/Chan/c2/send
select says hi to c2\n
EOF

sendsleep=$(( $RANDOM % 3 ))
recvsleep=$(( $RANDOM % 3 ))

echo "select cases:"
cat $LANGDIR/Select/s1/cases_json

(
sleep $sendsleep;
echo "start c1 write"
echo "c1 says hi to select" >> "$LANGDIR/Chan/c1/send"
)&

(
sleep $recvsleep;
echo "start c2 read"
cat "$LANGDIR/Chan/c2/recv"
)&

echo "start select"
cat "$LANGDIR/Select/s1/select"

for j in $(jobs -r -p); do
  kill $j 2>/dev/null
done
